//
//  XYHUDManager.m
//  XYCustomAlertView
//
//  Created by gao chenyang on 2019/11/1.
//  Copyright © 2019 gao chenyang. All rights reserved.
//

#import "XYHUDManager.h"
#define kScreen_height  [[UIScreen mainScreen] bounds].size.height
#define kScreen_width   [[UIScreen mainScreen] bounds].size.width
#define kDefaultRect     CGRectMake(0, 0, kScreen_width, kScreen_height)

#define kDefaultView [[UIApplication sharedApplication] keyWindow]

#define kGloomyBlackColor  [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2]
#define kGloomyClearCloler  [UIColor colorWithRed:1 green:1 blue:1 alpha:0]

/* 默认网络提示，可在这统一修改 */
static NSString *const kLoadingMessage = @"加载中";

/* 默认简短提示语显示的时间，在这统一修改 */
static CGFloat const kShowTime  = 2.0f;

@implementation XYHUDManager
XYGloomyView * gloomyView;//深色背景
UIView *prestrainView;//预加载view
BOOL isShowGloomy;//是否显示深色背景

//简短弹框的队列
NSMutableArray * toastArray;
//添加弹框view的队列
NSMutableArray * toastSuperViewArray;
#pragma mark -   类初始化
+ (void)initialize {
    if (self == [XYHUDManager self]) {
        //该方法只会走一次
        [self customView];
        // 转屏通知
        [[NSNotificationCenter defaultCenter] addObserver:[XYHUDManager shareInstance] selector:@selector(didChangeRotate:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    }
}

+(instancetype)shareInstance{
    static dispatch_once_t onceToken;
    static XYHUDManager * shareInstance = nil;
    dispatch_once(&onceToken, ^{
        shareInstance = [[XYHUDManager alloc] init];
    });
    return shareInstance;
}
- (void)didChangeRotate:(NSNotification*)notice {
    CGFloat width = 0;
    CGFloat height = 0;
    BOOL isPortrait = NO;
    if ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortrait
        || [[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortraitUpsideDown) {
        //竖屏
        isPortrait = YES;
    }
    if (prestrainView) {
        if (isPortrait) {
            //竖屏
            width = MIN(prestrainView.bounds.size.width, prestrainView.bounds.size.height);
            height = MAX(prestrainView.bounds.size.width, prestrainView.bounds.size.height);
        }else{
            width = MAX(prestrainView.bounds.size.width, prestrainView.bounds.size.height);
            height = MIN(prestrainView.bounds.size.width, prestrainView.bounds.size.height);
        }
    }else{
        width = kScreen_width;
        height = kScreen_height;
    }
    gloomyView.frame = CGRectMake(0, 0, width, height);
}
#pragma mark - 初始化gloomyView
+(void)customView {
    gloomyView = [[XYGloomyView alloc] init];
    gloomyView.contentMode = UIViewContentModeCenter;
    gloomyView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin
    | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    gloomyView.backgroundColor = kGloomyBlackColor;
    gloomyView.hidden = YES;
    isShowGloomy = NO;
    toastArray = [NSMutableArray array];
    toastSuperViewArray = [NSMutableArray array];
}
+ (void)showGloomy:(BOOL)isShow {
    isShowGloomy = isShow;
}
#pragma mark - 简短提示语
+(void)showBriefToast:(NSString *)toast{
    [self showBriefToast:toast isBlockUI:NO];
}

+ (void)showBriefToast:(NSString *)message time:(NSInteger)showTime {
    [self showBriefToast:message time:showTime isBlockUI:NO];
}

+ (void)showBriefToast:(NSString *) message
             isBlockUI:(BOOL)isBlockUI{
    [self showBriefToast:message time:kShowTime isBlockUI:isBlockUI];
}

+ (void)showBriefToast:(NSString *)message
                  time:(NSInteger)showTime
             isBlockUI:(BOOL)isBlockUI{
    [self showBriefToast:message time:showTime isBlockUI:isBlockUI inView:nil];
}

+ (void)showBriefToast:(NSString *)message
                  time:(NSInteger)showTime
             isBlockUI:(BOOL)isBlockUI
                inView:(nullable UIView *)view{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIView * superView = view ? :kDefaultView;
        XYProgressHUD *hud = [[XYProgressHUD alloc] initWithView:superView];
        hud.removeFromSuperViewOnHide = YES;
        hud.isBlockUI = isBlockUI;
        hud.detailsLabelText = message;
        hud.detailsLabelFont = [UIFont systemFontOfSize:14];
        hud.animationType = XYProgressHUDAnimationFade;
        hud.mode = XYProgressHUDModeText;
        hud.margin = 20.f;
        hud.showTime = showTime;
        @synchronized (toastArray) {
            [toastArray addObject:hud];
            [toastSuperViewArray addObject:superView];
            if (toastArray.count == 1) {
                [self showBriefToast];
            }
        }
    });
}

+ (void)showInTellToastAttriString:(NSAttributedString *)string InView:(UIView *)view completion:(void (^)(XYProgressHUD * _Nonnull))completion {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIView * superView = view ? :kDefaultView;
        XYProgressHUD *hud = [[XYProgressHUD alloc] initWithView:superView];
        hud.removeFromSuperViewOnHide = YES;
        hud.isBlockUI = NO;
        hud.attriDetailsLabelText = string;
        hud.detailsLabelFont = [UIFont systemFontOfSize:14];
        hud.animationType = XYProgressHUDAnimationFade;
        hud.mode = XYProgressHUDModeText;
        hud.margin = 20.f;
        hud.showTime = INT_MAX;
        @synchronized (toastArray) {
            [toastArray addObject:hud];
            [toastSuperViewArray addObject:superView];
            if (toastArray.count == 1) {
                [self showBriefToast];
            }
        }
        if (completion) {
            completion(hud);
        }
    });
}

+(void)showBriefToast{
    @synchronized (toastArray) {
        if (toastArray.count > 0) {
            XYProgressHUD * hud = (XYProgressHUD *)toastArray.firstObject;
            UIView * view = toastSuperViewArray.firstObject;
            [view addSubview:hud];
            [hud show:YES];
            [hud hide:NO afterDelay:hud.showTime];
            hud.completionBlock = ^{
                @synchronized (toastArray) {
                    if (toastArray.count > 0) {
                        [toastSuperViewArray removeObjectAtIndex:0];
                        [toastArray removeObjectAtIndex:0];//移除第一个
                        [XYHUDManager showBriefToast];
                    }
                }
            };
        }
    }
}

+(void)clearAllToast{
    @synchronized (toastArray) {
        [toastSuperViewArray removeAllObjects];
        [toastArray removeAllObjects];
    }
}
#pragma mark - 长时间的提示语
+ (void)showPermanentMessage:(NSString *)message
                      inView:(nullable UIView *) view
             isAvalibleTouch:(BOOL)isAvalibleTouch
           hideToastComplete:(nullable HideToastComplete)complete{
    dispatch_async(dispatch_get_main_queue(), ^{
        prestrainView = view;
        gloomyView.isAvalibleTouch = isAvalibleTouch;
//        gloomyView.hideToastComplete = complete;
        gloomyView.frame = view ? CGRectMake(0, 0, view.frame.size.width, view.frame.size.height):
        kDefaultRect;
        XYProgressHUD *hud = [XYProgressHUD showHUDAddedTo:gloomyView animated:YES];
        hud.labelText = message;
        hud.completionBlock = complete;
        hud.labelFont = [UIFont systemFontOfSize:14];
        hud.animationType = XYProgressHUDAnimationZoom;
        hud.mode = XYProgressHUDModeCustomView;
        hud.removeFromSuperViewOnHide = YES;
        hud.mode = XYProgressHUDModeText;
        [gloomyView addSubview:hud];
        [self showClearGloomyView];
        [hud show:YES];
    });
}
#pragma mark - 网络加载提示用
+ (void) showLoadingInView:(nullable UIView *)view{
    [self showLoadingWithTitle:kLoadingMessage inView:view isAvalibleTouch:NO hideToastComplete:nil];
}

+ (void) showLoadingWithTitle:(NSString *) title
                       inView:(nullable UIView *)view
            hideToastComplete:(nullable HideToastComplete)complete{
    [self showLoadingWithTitle:title inView:view isAvalibleTouch:YES hideToastComplete:complete];
}

+ (void)showLoadingWithTitle:(NSString *)title
                      inView:(nullable UIView *)view
             isAvalibleTouch:(BOOL)isAvalibleTouch
           hideToastComplete:(nullable HideToastComplete)complete{
    dispatch_async(dispatch_get_main_queue(), ^{
        prestrainView = view;
        XYProgressHUD *hud = [[XYProgressHUD alloc] initWithView:gloomyView];
        hud.labelText = title;
        hud.labelFont = [UIFont systemFontOfSize:14];
        hud.removeFromSuperViewOnHide = YES;
        gloomyView.isAvalibleTouch = isAvalibleTouch;
        gloomyView.hideToastComplete = complete;
        gloomyView.frame = view ? CGRectMake(0, 0, view.frame.size.width, view.frame.size.height):
        kDefaultRect;
        if (isShowGloomy) {
            [self showBlackGloomyView];
        }else {
            [self showClearGloomyView];
        }
        [gloomyView addSubview:hud];
        [hud show:YES];
    });
}

#pragma mark - 加载在window上的提示框
+(void)showLoading{
    [self showLoadingInView:nil];
}

+ (void)showLoadingWithTitle:(NSString *)title{
    [self showLoadingWithTitle:title inView:nil isAvalibleTouch:NO hideToastComplete:nil];
}

+(void)showPermanentToast:(NSString *)toast{
    [self showPermanentMessage:toast inView:nil isAvalibleTouch:NO hideToastComplete:nil];
}

#pragma mark - 自定义网络加载提示
+ (void) showCustomLoadingInView:(nullable UIView *)view{
    [self showCustomLoadingWithTitle:kLoadingMessage inView:view isAvalibleTouch:NO hideToastComplete:nil];
}

+ (void) showCustomLoadingWithTitle:(nullable NSString *)title
                             inView:(nullable UIView *)view
                  hideToastComplete:(nullable HideToastComplete)complete{
    [self showCustomLoadingWithTitle:title inView:view isAvalibleTouch:YES hideToastComplete:complete];
}

+ (void)showCustomLoadingWithTitle:(nullable NSString *)title
                            inView:(nullable UIView *)view
                   isAvalibleTouch:(BOOL)isAvalibleTouch
                 hideToastComplete:(nullable HideToastComplete)complete{
    [self showCustomLoadingWithTitle:title imageName:nil customRect:CGRectMake(0, 0, 50, 50) labelColor:[UIColor whiteColor] hudBackColor:nil inView:view isAvalibleTouch:isAvalibleTouch hideToastComplete:complete];
}
//--------------项目专用--------------------
+ (void)showCustomBlueLoadingWithTitle:(nullable NSString *)title
                               isLarge:(BOOL)isLarge
                                inView:(nullable UIView *)view
                       isAvalibleTouch:(BOOL)isAvalibleTouch
                     hideToastComplete:(nullable HideToastComplete)complete{
    [self showCustomLoadingWithTitle:title imageName:@"standard_alert_icon_loading_white.png" customRect:isLarge ?CGRectMake(0, 0, 50, 50) : CGRectMake(0, 0, 40, 40) labelColor:[UIColor lightGrayColor] hudBackColor:[UIColor whiteColor] inView:view isAvalibleTouch:isAvalibleTouch hideToastComplete:complete];
}

+ (void)showCustomWhiteLoadingWithTitle:(nullable NSString *)title
                                 inView:(nullable UIView *)view
                        isAvalibleTouch:(BOOL)isAvalibleTouch
                      hideToastComplete:(nullable HideToastComplete)complete{
    [self showCustomLoadingWithTitle:title imageName:@"standard_alert_icon_loading_black.png" customRect:CGRectMake(0, 0, 40, 40) labelColor:[UIColor whiteColor] hudBackColor:nil inView:view isAvalibleTouch:isAvalibleTouch hideToastComplete:complete];
}

+ (void)showCustomLoadingWithTitle:(nullable NSString *)title
                         imageName:(nullable NSString *)imageName
                        customRect:(CGRect)customRect
                        labelColor:(nullable UIColor *)labelColor
                      hudBackColor:(nullable UIColor *)hudBackColor
                            inView:(nullable UIView *)view
                   isAvalibleTouch:(BOOL)isAvalibleTouch
                 hideToastComplete:(nullable HideToastComplete)complete{
    dispatch_async(dispatch_get_main_queue(), ^{
        prestrainView = view;
        gloomyView.isAvalibleTouch = isAvalibleTouch;
        //        gloomyView.hideToastComplete = complete;
        gloomyView.frame = view ? CGRectMake(0, 0, view.frame.size.width, view.frame.size.height):
        kDefaultRect;
        XYProgressHUD *hud = [[XYProgressHUD alloc] initWithView:gloomyView];
        XYRotationLoopProgressView * rotationLoopProgressView = [[XYRotationLoopProgressView alloc] initWithFrame:customRect];
        rotationLoopProgressView.imageName = imageName;
        hud.color = hudBackColor;
        hud.customView = rotationLoopProgressView;
        hud.completionBlock = complete;
        hud.removeFromSuperViewOnHide = YES;
        hud.animationType = XYProgressHUDAnimationFade;
        hud.labelText = title;
        hud.labelColor = labelColor;
        hud.labelFont = [UIFont systemFontOfSize:14];
        hud.mode = XYProgressHUDModeCustomView;
        if (isShowGloomy) {
            [self showBlackGloomyView];
        }else {
            [self showClearGloomyView];
        }
        [gloomyView addSubview:hud];
        [hud show:YES];
    });
}
#pragma mark - 下载进度视图
+ (XYLoopProgressView *)showProgressViewWithTitle:(NSString *)title{
    return [self showProgressViewWithTitle:title inView:nil];
}
+ (XYLoopProgressView *)showProgressViewWithTitle:(NSString *)title inView:(nullable UIView *)view{
    XYLoopProgressView * loopProgressView = [[XYLoopProgressView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    loopProgressView.lineWidth = 5;
    loopProgressView.isShowText = YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        prestrainView = view;
        gloomyView.frame = view ? CGRectMake(0, 0, view.frame.size.width, view.frame.size.height):
        kDefaultRect;
        XYProgressHUD *hud = [[XYProgressHUD alloc] initWithView:gloomyView];
        hud.customView = loopProgressView;
        hud.removeFromSuperViewOnHide = YES;
        hud.animationType = XYProgressHUDAnimationFade;
        hud.labelText = title;
        hud.margin = 10;
        hud.labelFont = [UIFont systemFontOfSize:14];
        hud.mode = XYProgressHUDModeCustomView;
        [self showClearGloomyView];
        [gloomyView addSubview:hud];
        [hud show:YES];
    });
    return loopProgressView;
}

#pragma mark -   GloomyView背景色
+ (void)showBlackGloomyView {
//    gloomyView.userInteractionEnabled = gloomyView.isAvalibleTouch;
    gloomyView.backgroundColor = kGloomyBlackColor;
    [self gloomyConfig];
}
+ (void)showClearGloomyView {
//    gloomyView.userInteractionEnabled = gloomyView.isAvalibleTouch;
    gloomyView.backgroundColor = kGloomyClearCloler;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self gloomyConfig];
    });
}
#pragma mark -   决定GloomyView add到已给view或者window上
+ (void)gloomyConfig {
    gloomyView.hidden = NO;
    gloomyView.alpha = 1;
    if (prestrainView) {
        [prestrainView addSubview:gloomyView];
    }else {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        if (![window.subviews containsObject:gloomyView]) {
            [window addSubview:gloomyView];
        }
    }
}
#pragma mark - 隐藏提示框
+(void)hideToast{
    [self hideToastAnimated:NO];
}

+(void)hideToastAnimated:(BOOL)animated{
    dispatch_async(dispatch_get_main_queue(), ^{
        for (XYProgressHUD *hud in [XYHUDManager allsHUDForView:gloomyView]) {
            [hud hide:animated];
            if (animated) {
                [UIView animateWithDuration:0.5 animations:^{
                    gloomyView.frame = CGRectZero;
                    gloomyView.center = prestrainView ? prestrainView.center: [UIApplication sharedApplication].keyWindow.center;
                    gloomyView.alpha = 0;
                    hud.alpha = 0;
                } completion:^(BOOL finished) {
                    [hud removeFromSuperview];
                }];
            }else{
                gloomyView.frame = CGRectZero;
                gloomyView.center = prestrainView ? prestrainView.center: [UIApplication sharedApplication].keyWindow.center;
                gloomyView.alpha = 0;
                [hud removeFromSuperview];
                [gloomyView removeFromSuperview];
            }
        }
    });
}
#pragma mark -   获取view上的hud
+ (XYProgressHUD *)HUDForView:(UIView *)view {
    NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator];
    for (UIView *subview in subviewsEnum) {
        if ([subview isKindOfClass:[XYProgressHUD class]]) {
            return (XYProgressHUD *)subview;
        }
    }
    return nil;
}
+ (NSArray *)allsHUDForView:(UIView *)view {
    NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator];
    NSMutableArray * huds = [NSMutableArray array];
    for (UIView *subview in subviewsEnum) {
        if ([subview isKindOfClass:[XYProgressHUD class]]) {
            [huds addObject:subview];
        }
    }
    return huds;
}
@end

@implementation XYGloomyView

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (self.isAvalibleTouch) {
        [XYHUDManager hideToast];
    }
//    if (self.hideToastComplete) {
//        self.hideToastComplete();
//    }
}

@end
